<template>
    <div class="app-container">
      <el-form :model="queryParams" ref="queryRef" :inline="true" v-show="showSearch" label-width="68px">
        <el-form-item label="结算编码" prop="settlementCode">
          <el-input
            v-model="queryParams.settlementCode"
            placeholder="请输入结算编码"
            clearable
            style="width: 240px"
            @keyup.enter="handleQuery"
          />
        </el-form-item>
       
        <el-form-item label="结算方式" prop="settlementMethod">
          <el-select v-model="queryParams.settlementMethod" placeholder="请选择结算方式" clearable style="width: 240px">
            <el-option
              v-for="dict in settlement_ways"
              :key="dict.value"
              :label="dict.label"
              :value="dict.value"
            />
          </el-select>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" icon="Search" @click="handleQuery">搜索</el-button>
          <el-button icon="Refresh" @click="resetQuery">重置</el-button>
        </el-form-item>
      </el-form>
  
      <el-row :gutter="10" class="mb8">
        <el-col :span="1.5">
          <el-button
            type="warning"
            plain
            icon="Download"
            @click="handleExport"
            v-hasPermi="['record:record:export']"
          >导出</el-button>
        </el-col>
        <right-toolbar v-model:showSearch="showSearch" @queryTable="getList"></right-toolbar>
      </el-row>
  
      <!-- 表格数据 -->
      <el-table v-loading="loading" :data="filteredRecordList" @selection-change="handleSelectionChange" :single-select="true">
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column label="结算编码" prop="settlementCode" width="120" />
        <el-table-column label="合作方编码" prop="partnerCode" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="合作方类型" prop="partnerType" width="100" />
        <el-table-column label="结算总金额" prop="settlementAmount" width="120" />
        <el-table-column label="结算方式" align="center" width="120">
          <template #default="scope">
            <dict-tag :options="settlement_ways" :value="scope.row.settlementMethod"/>
          </template>
        </el-table-column>
        <el-table-column label="协议编码" prop="agreementCode" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="货币单位" prop="currencyUnit" width="100" />
        <el-table-column label="实际支付日期" align="center" prop="paymentDate" width="180">
          <template #default="scope">
            <span>{{ parseTime(scope.row.paymentDate, '{y}-{m}-{d}') }}</span>
          </template>
        </el-table-column>
        <el-table-column label="结算状态" align="center" width="100">
          <template #default="scope">
            <span>{{ scope.row.settlementStatus }}</span>
          </template>
        </el-table-column>
        <el-table-column label="备注信息" prop="remark" :show-overflow-tooltip="true" width="150" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template #default="scope">
            <el-button
              v-if="scope.row.settlementStatus === '待确认'"
              link
              type="primary"
              icon="Check"
              @click="handleConfirm(scope.row)"
             
            >确认</el-button>
            <el-button
  v-if="scope.row.settlementStatus === '待确认'"
  link
  type="danger"
  icon="Close"
  @click="handleReject(scope.row)"
 
>驳回</el-button>

            
            <el-button
              v-if="scope.row.settlementStatus === '待支付'"
              link
              type="primary"
              icon="Money"
              @click="handlePayment(scope.row)"
             
            >支付</el-button>
          </template>
        </el-table-column>
      </el-table>
  
      <pagination
        v-show="total > 0"
        :total="total"
        v-model:page="queryParams.pageNum"
        v-model:limit="queryParams.pageSize"
        @pagination="getList"
      />
  
      <!-- 确认对话框 -->
      <el-dialog :title="confirmTitle" v-model="confirmOpen" width="600px" append-to-body>
        <el-form :model="confirmForm" label-width="120px" disabled>
          <el-form-item label="结算编码">
            <el-input v-model="confirmForm.settlementCode" />
          </el-form-item>
          <el-form-item label="合作方编码">
            <el-input v-model="confirmForm.partnerCode" />
          </el-form-item>
          <el-form-item label="结算总金额">
            <el-input v-model="confirmForm.settlementAmount" />
          </el-form-item>
          <el-form-item label="结算方式">
            <el-select v-model="confirmForm.settlementMethod" placeholder="请选择结算方式">
              <el-option
                v-for="dict in settlement_ways"
                :key="dict.value"
                :label="dict.label"
                :value="dict.value"
              />
            </el-select>
          </el-form-item>
          <el-form-item label="协议编码">
            <el-input v-model="confirmForm.agreementCode" />
          </el-form-item>
          <el-form-item label="货币单位">
            <el-input v-model="confirmForm.currencyUnit" />
          </el-form-item>
          <el-form-item label="备注信息">
            <el-input v-model="confirmForm.remark" type="textarea" />
          </el-form-item>
          <el-form-item label="结算状态">
            <el-input v-model="confirmForm.settlementStatus" />
          </el-form-item>
          <el-form-item label="实际支付日期">
            <el-input v-model="confirmForm.paymentDate" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitConfirm">确认</el-button>
            <el-button @click="confirmOpen = false">关 闭</el-button>
          </div>
        </template>
      </el-dialog>
  
      <!-- 支付对话框 -->
      <el-dialog :title="paymentTitle" v-model="paymentOpen" width="600px" append-to-body>
        <el-form ref="paymentRef" :model="paymentForm" :rules="paymentRules" label-width="100px">
          <el-form-item label="支付方式" prop="paymentMethod">
            <el-select v-model="paymentForm.paymentMethod" placeholder="请选择支付方式">
              <el-option label="支付宝" value="alipay" />
              <el-option label="微信" value="wechat" />
              <el-option label="银联" value="unionpay" />
            </el-select>
          </el-form-item>
          <el-form-item label="支付金额" prop="paymentAmount">
            <el-input v-model="paymentForm.paymentAmount" placeholder="请输入支付金额" />
          </el-form-item>
          <el-form-item label="备注信息" prop="remark">
            <el-input v-model="paymentForm.remark" type="textarea" placeholder="请输入内容" />
          </el-form-item>
        </el-form>
        <template #footer>
          <div class="dialog-footer">
            <el-button type="primary" @click="submitPayment">确 定</el-button>
            <el-button @click="paymentOpen = false">取 消</el-button>
          </div>
        </template>
      </el-dialog>
    </div>
  </template>
  
  <script setup name="Record">
 import { listRecord, updateRecordStatus } from "@/api/record/record";
import { ref, reactive, toRefs, computed, getCurrentInstance } from 'vue';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/store/modules/user';

const { proxy } = getCurrentInstance();
const { settlement_ways } = proxy.useDict('settlement_ways');

const userStore = useUserStore();
const userRole = ref(userStore.roles);

const recordList = ref([]);
const open = ref(false);
const loading = ref(true);
const showSearch = ref(true);
const ids = ref([]);
const selectedRecord = ref(null);
const total = ref(0);
const title = ref("");
const confirmOpen = ref(false);
const confirmTitle = ref("");
const confirmForm = ref({});
const paymentOpen = ref(false);
const paymentTitle = ref("");
const paymentForm = ref({
  paymentMethod: '',
  paymentAmount: '',
  remark: ''
});
const paymentRules = ref({
  paymentMethod: [
    { required: true, message: "支付方式不能为空", trigger: "change" }
  ],
  paymentAmount: [
    { required: true, message: "支付金额不能为空", trigger: "blur" }
  ],
  remark: [
    { required: true, message: "备注信息不能为空", trigger: "blur" }
  ],
});

const data = reactive({
  queryParams: {
    pageNum: 1,
    pageSize: 10,
    settlementCode: null,
    partnerCode: null,
    settlementMethod: null,
    settlementStatus: null,
  },
  settlementForm: {
    partnerCode: '',
    settlementAmount: 0,
    settlementMethod: '',
    agreementCode: '',
    currencyUnit: '',
    settlementStatus: '',
    remark: ''
  },
  settlementRules: {
    settlementMethod: [
      { required: true, message: "结算方式不能为空", trigger: "blur" }
    ],
    agreementCode: [
      { required: true, message: "协议编码不能为空", trigger: "blur" }
    ],
    currencyUnit: [
      { required: true, message: "货币单位不能为空", trigger: "blur" }
    ],
    settlementStatus: [
      { required: true, message: "结算状态不能为空", trigger: "blur" }
    ],
    remark: [
      { required: true, message: "备注信息不能为空", trigger: "blur" }
    ],
  },
  settlementDetailList: [] // 初始化为空数组
});

const { queryParams, settlementForm, settlementRules, settlementDetailList } = toRefs(data);

// 计算属性，根据用户角色过滤结算记录
const filteredRecordList = computed(() => {
  if (userRole.value.includes('distributor')) {
    return recordList.value.filter(record => record.partnerType === '经销商');
  }
  // 其他角色可以展示所有记录或特定记录
  return recordList.value;
});

/** 查询结算记录列表 */
function getList() {
  loading.value = true;
  listRecord(queryParams.value).then(response => {
    recordList.value = response.rows.map(row => ({
      ...row,
      partnerType: getPartnerType(row.partnerCode)
    }));
    total.value = response.total;
    loading.value = false;
  });
}
  
  // 取消按钮
  function cancel() {
    open.value = false;
    reset();
  }
  
  // 表单重置
  function reset() {
    settlementForm.value = {
      partnerCode: '',
      settlementAmount: 0,
      settlementMethod: '',
      agreementCode: '',
      currencyUnit: '',
      settlementStatus: '',
      remark: ''
    };
    settlementDetailList.value = [];
    confirmOpen.value = false;
    paymentOpen.value = false;
    paymentForm.value = {
      paymentMethod: '',
      paymentAmount: '',
      remark: ''
    };
  }
  
  /** 搜索按钮操作 */
  function handleQuery() {
    queryParams.value.pageNum = 1;
    getList();
  }
  
  /** 重置按钮操作 */
  function resetQuery() {
    proxy.resetForm("queryRef");
    handleQuery();
  }
  
  // 多选框选中数据
  function handleSelectionChange(selection) {
    selectedRecord.value = selection.length > 0 ? selection[0] : null;
  }
  
  /** 确认操作 */
  function handleConfirm(row) {
    confirmForm.value = {
      ...row,
      paymentDate: parseTime(row.paymentDate, '{y}-{m}-{d}')
    };
    confirmTitle.value = `确认结算记录 - ${row.settlementCode}`;
    confirmOpen.value = true;
  }
  
  /** 提交确认操作 */
  function submitConfirm() {
    updateRecordStatus(confirmForm.value.settlementCode, '待支付').then(() => {
      ElMessage.success('结算状态更新为“待支付”');
      confirmOpen.value = false;
      reset();
      getList();
    }).catch(error => {
      ElMessage.error('结算状态更新失败');
    });
  }
  
  /** 支付操作 */
  function handlePayment(row) {
    paymentForm.value = {
      paymentMethod: '',
      paymentAmount: row.settlementAmount,
      remark: ''
    };
    paymentTitle.value = `支付结算记录 - ${row.settlementCode}`;
    paymentOpen.value = true;
  }
  
  /** 提交支付操作 */
  function submitPayment() {
    proxy.$refs["paymentRef"].validate(valid => {
      if (!valid) return;
      updateRecordStatus(confirmForm.value.settlementCode, '已支付').then(() => {
        ElMessage.success('结算状态更新为“已支付”');
        paymentOpen.value = false;
        reset();
        getList();
      }).catch(error => {
        ElMessage.error('结算状态更新失败');
      });
    });
  }
  
  /** 导出按钮操作 */
  function handleExport() {
    proxy.download('record/record/export', {
      ...queryParams.value
    }, `record_${new Date().getTime()}.xlsx`);
  }
  
  /** 根据合作方编码获取合作方类型 */
  function getPartnerType(partnerCode) {
    if (partnerCode.startsWith('DEALER')) {
      return '经销商';
    } else if (partnerCode.startsWith('LEADER')) {
      return '团长';
    } else if (partnerCode.startsWith('BLOGGER')) {
      return '博主';
    } else if (partnerCode.startsWith('LOGISITICS')) {
      return '物流商';
    } else if (partnerCode.startsWith('SUPPLY')) {
      return '供货商';
    } else {
      return '未知类型';
    }
  }

  /** 驳回操作 */
function handleReject(row) {
  proxy.$modal.confirm(`确认要驳回结算记录 - ${row.settlementCode} 吗?`).then(function () {
    updateRecordStatus(row.settlementCode, '已驳回').then(() => {
      ElMessage.success('结算记录已驳回');
      getList();
    }).catch(error => {
      ElMessage.error('驳回结算记录失败');
    });
  }).catch(() => {});
}
  
  getList();
  </script>